package framework.web;

import framework.pojo.Cart;
import framework.pojo.Cart_item;
import framework.pojo.Item;
import framework.pojo.Record;
import framework.pojo.User;
import framework.service.ItemService;
import framework.service.RecordService;
import framework.service.impl.ItemServiceImp;
import framework.service.impl.RecordServiceImp;

import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.Map;
import java.util.Properties;

public class OrderServlet extends BaseServlet {

    protected static MimeMessage CreateMessage(Session session, String sendMail, String receiveMail) throws Exception {
        //设置邮件的寄信人，收信人，邮件主题，邮件内容，发送日期。
        MimeMessage message = new MimeMessage(session);

        message.setFrom(new InternetAddress(sendMail, "kangkang商城", "UTF-8"));

        message.setRecipients(MimeMessage.RecipientType.TO, String.valueOf(new InternetAddress(receiveMail, "亲爱的用户", "UTF-8")));

        message.setSubject("来自kangkang商城的购买通知", "UTF-8");

        message.setContent(" Dear customer, the goods you bought in kangkang mall have been delivered. Wishing you a happy shopping!", "text/html; charset=UTF-8");

        message.setSentDate(new Date());

        message.saveChanges();

        return message;
    }

    //发送邮件
    protected void SendMail(String receiveMailAccount) {
        //设置发送方的邮件账户以及中间服务器的ip，协议，发送邮件
        String myEmailAccount = "kangkang20211202@163.com";
        String myEmailPassword = "!qwe122699";
        String myEmailSMTPHost = "smtp.163.com";


        Properties props = new Properties();
        props.setProperty("mail.transport.protocol", "smtp");
        props.setProperty("mail.smtp.host", myEmailSMTPHost);

        Session session = Session.getInstance(props);

        session.setDebug(true);

        try {
            MimeMessage message = CreateMessage(session, myEmailAccount, receiveMailAccount);

            Transport transport = session.getTransport();

            transport.connect(myEmailSMTPHost, myEmailAccount, "UEJUACXJJXKEOCRE");

            transport.sendMessage(message, message.getAllRecipients());

            transport.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 调用SendMail函数发送邮件并修改销量和库存，修改购买记录
     * @throws ServletException
     * @throws IOException
     */
    protected void pay(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        User u = (User) req.getSession().getAttribute("user");
        Cart c = (Cart) req.getSession().getAttribute("cart");
        RecordService recordService = new RecordServiceImp();
        ItemService itemService = new ItemServiceImp();

        //支付成功直接调用发送邮件
        SendMail(u.getEmail());

        for (Map.Entry<Integer, Cart_item> item : c.getItems().entrySet()) {

            /*修改商品的销量和存货*/
            Item item1 = itemService.queryItemById(item.getValue().getId());
            item1.setSales(item1.getSales() + item.getValue().getCount());
            item1.setStock(item1.getStock() - item.getValue().getCount());
            itemService.updateItem(item1);

            Record entry = new Record(u.getId(), item.getValue().getId(), item.getValue().getName(), true);
            System.out.println(entry);
            recordService.AddRecord(entry);
            req.getSession().removeAttribute("cart");
        }
        req.getRequestDispatcher("/page/user/pay.jsp").forward(req, resp);
    }
}

